/**
 * Copyright (C) 2013 SHANGHAI VOLKSWAGEN, All rights reserved.
 * License version 1.0, a copy of which has been included with this.
 *
 * @File name：com.market.order.server.consumer.MsgConsumer
 * @Create on：2024/2/28
 * @Author：liuchang
 */
package com.market.order.server.consumer;

import com.market.order.server.config.MqConfig;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * <p>ClassName：MsgConsumer</p >
 * <p>Description：</p >
 * <p>Author：liuchang</p >
 * <p>Date：2024/2/28</p >
 */
@Component
@Log4j2
@RabbitListener(queues = MqConfig.MESSAGE_QUEUE)
public class MsgConsumer {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @RabbitHandler
    public void taker(String phone, Message message, Channel channel) throws IOException {
        log.info("收到的手机号是：{}"+phone);
        String messageId = message.getMessageProperties().getMessageId();
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        redisTemplate.opsForValue().set("retry"+messageId,deliveryTag+"");


        try {
            Long add = redisTemplate.opsForSet().add("repeat" + messageId, messageId);
            if (add==1){
                redisTemplate.opsForValue().set(phone,"你还有订单未支付，请及时支付");
                channel.basicAck(deliveryTag,false);
            }else {
                channel.basicReject(deliveryTag,false);
                log.info("消息不能重复消费");
            }
        } catch (Exception e) {
            String s = redisTemplate.opsForValue().get("retry" + messageId);
            long l = Long.parseLong(s);
            if (deliveryTag==(l+2)){
                log.info("消息不能再消费，不能进入消息队列");
                channel.basicNack(deliveryTag,false,false);
            }else {
                log.info("消息继续消费，再次进入消息队列");
                channel.basicNack(deliveryTag,false,true);
            }
        }

    }

}
